<?php

namespace Apps\Manage\Controllers;
use Apps\Common\Models\BackendOperator;
use Apps\Common\Models\BeautyParlor;
use Apps\Common\Models\CosPointBp;
use Apps\Common\Models\OmBanner;
use Apps\Common\Models\OmQuestionAnswerUser;
use Apps\Common\Models\SysAreaZipDistrictPhonecode;
use Apps\Common\Models\SysOpenCity;
use Apps\Common\Models\UserBase;
use Apps\Common\Models\UserFeedback;
use Phalcon\Db\RawValue;
use PhalconPlus\Common\ResponseResult;
use PhalconPlus\Common\ResponseResultStatus;
use Apps\Common\Libs\UploadPic;
use Apps\Common\Models\QuestionReport;
use Apps\Common\Models\Advertisement;
use Phalcon\Mvc\Model;
use Phalcon\Http\Response;
use Apps\Common\Libs\PicUrl;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Libs\SysArea;
use PhalconPlus\Common\Util;


/**
 * 运营管理
 * @author     chenxiaolin
 * @date        2016年1月19日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class OmController extends BaseController
{
    public function initialize()
    {
        parent::initialize();
        $this->setMainNav('om');
    }

    /**
     * 开通的城市
     * @return \Phalcon\Mvc\Model\Criteria
     */
    private function openCityList()
    {
        return SysOpenCity::find('city_state = 1');
    }

    public function indexAction()
    {
        $this->response->redirect('om/bannerList');
    }

    /**
     * 1.1版本： 首页轮播banner位
     */
    public function bannerIndexAction()
    {
        $this->setLeftNav('bannerIndex');

        $key = 'index_pics';
        $req = $this->request;
        if(!$req->isPost()) {
            $filterCity = intval($req->getQuery('filterCity', null, 0));
            $this->view->setVar('openCity', $this->openCityList());
            $this->view->setVar('filterCity', $filterCity);
            $data = '[]';
            if($filterCity > 0) {
                $bannerData = OmBanner::query()
                    ->columns('banner_data')
                    ->where('city_id = :cid: AND banner_name = :key:', ['cid' => $filterCity, 'key' => $key])
                    ->execute()
                    ->getFirst();
               
                if($bannerData) {
                    $data = $bannerData->banner_data;
                }
            }
            $this->view->setVar('data', json_decode($data, true));
            return;
        } else {
        	
            $response = new ResponseResult();
            $data = $req->getPost('data', null, 0);
            
            $city = intval($req->getPost('city', null, 0));
            if(empty($data) || $city < 1) {
                return $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常');
            }

            $bannerData = OmBanner::query()
                ->where('city_id = :cid: AND banner_name = :key:', ['cid' => $city, 'key' => $key])
                ->execute()
                ->getFirst();
            //判断排序不能重复
            $data1 = json_decode($data,true);//表单提交
            
            $i = 0;
            foreach ($data1 as $k => $v){
            	$sortArr1[$i] = $v['link_sort'];
            	$i++;         	          	
            }
            switch (count($sortArr1)){
            	case 0:
            	case 1:
            		break;
            	case 2:
            		if($sortArr1[0] == $sortArr1[1]){
            			$response->sendError(ResponseResultStatus::BUSINESS, '排序已经存在！');
            			return $response;
            		}
            	case 3:
            		if($sortArr1[0] == $sortArr1[1] || $sortArr1[0] == $sortArr1[2] || $sortArr1[1] == $sortArr1[2]){
            			$response->sendError(ResponseResultStatus::BUSINESS, '排序已经存在！');
            			return $response;
            		}
            		
            }
 
            if($bannerData) {
                $bannerData->update(['banner_data'=>$data, 'banner_update_time' => new RawValue('NOW()')]);
                $response->sendResult($bannerData->banner_id);
            } else {
                $bannerData = new OmBanner();
                $bannerData->city_id = $city;
                $bannerData->banner_name = $key;
                $bannerData->banner_data = $data;
               
                if($bannerData->save() == false) {
                    $this->databaseErrorLog($bannerData);
                    $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常');
                } else {
                    $response->sendResult($bannerData->banner_id);
                }
            }
            return $response;
        }
    }

    
    /**
     *1.1版本： 首页推荐美容院
     */
    public function bannerBpAction()
    {
        $this->setLeftNav('bannerBp');
        $key = 'index_bp';
        $req = $this->request;
        if(!$req->isPost()) {
            $filterCity = intval($req->getQuery('City',null, 0));
            $this->view->setVar('openCity', $this->openCityList());
            $this->view->setVar('filterCity', $filterCity);
            $page = intval($req->getQuery('page', null, 1));
            $page = $page > 0 ? $page : 1;
            $limit = $this->pageNavLimit;
            $offset = $limit * ($page - 1);
            $count=CosPointBp::count(['conditions'=>"addr = $filterCity"]);
            $list=CosPointBp::query()
           		->where("addr = '$filterCity'")
           		->limit($limit, $offset)
            	->execute()
            	->toArray();
            foreach ($list as $k=>$v){
            	$tmp=SysOpenCity::findFirst("city_id = ".$list[$k]['addr'])->toArray();
            	$list[$k]['city_name']=$tmp['city_name'];
            	$list[$k]['img_url']="http://img.meelier.com/".$list[$k]['img_url'];
            }
            $this->view->setVar("total",$count);
            $this->view->setVar("limit",$limit);
            $this->view->setVar("page",$page);
            $this->view->setVar("list",$list);
            /* 
            $data = null;
            $bpData = [];
            if($filterCity > 0) {
                $bannerData = OmBanner::query()
                    ->columns('banner_data')
                    ->where('city_id = :cid: AND banner_name = :key:', ['cid' => $filterCity, 'key' => $key])
                    ->execute()
                    ->getFirst();
                if($bannerData) {
                    $data = $bannerData->banner_data;
                }
            }
            if($data != null) {
                $columns = [
                    'bp_id',
                    'bp_name',
                    'bp_cover',
                    'bp_address',
                    'bp_district',
                    'FULL_NAME district',
                    'bp_coordinate',
                    'bp_tel',
                    'bp_intro',
                    'bp_state',
                    'bp_is_sell',
                    'bp_medal',
                    'bp_addtime'
                ];
                $bpData = BeautyParlor::query()
                    ->columns($columns)
                    ->leftJoin('Apps\Common\Models\SysAreaZipDistrictPhonecode', 'K_ID=bp_district', 'area')
                    ->where('bp_id = :id:', ['id'=>$data])
                    ->execute();
            }
            $this->view->setVar('data', $data);
            $this->view->setVar('bpData', $bpData); */

            $this->view->setVar('filterCity', $filterCity);
            return;
        } else {
        	$response = new ResponseResult();
        	
        	
            $response = new ResponseResult();
            $bpId = intval($req->getPost('bpid', null, 0));
            $city = intval($req->getPost('city', null, 0));
            if($bpId < 1 || $city < 1) {
                return $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常');
            }
            // 查询美容院是否存在
            if(BeautyParlor::count('bp_id = ' . $bpId) == 0) {
                return $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '美容院不存在！');
            }
            $bannerData = OmBanner::query()
                ->where('city_id = :cid: AND banner_name = :key:', ['cid' => $city, 'key' => $key])
                ->execute()
                ->getFirst();
            if($bannerData) {
                $bannerData->update(['banner_data'=>$bpId, 'banner_update_time' => new RawValue('NOW()')]);
                $response->sendResult($bannerData->banner_id);
            } else {
                $bannerData = new OmBanner();
                $bannerData->city_id = $city;
                $bannerData->banner_name = $key;
                $bannerData->banner_data = $bpId;
                if($bannerData->save() == false) {
                    $this->databaseErrorLog($bannerData);
                    $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常');
                } else {
                    $response->sendResult($bannerData->banner_id);
                }
            }
            return $response;
        }
    }

    /**
     * Banner列表
     * @date: 2016年1月5日 
     * @author: chenxiaolin
     */
    public function bannerListAction(){
        $this -> setLeftNav('bannerList');
        $req = $this -> request;
        $page = intval($req->getQuery('page', null, 1));
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $offset = $limit * ($page - 1);
        
        $banner_name = $req->getQuery('banner_name',null,-10000);
        $filterCity = intval ( $req->getQuery ( 'filterCity', null, - 10000 ) );
        
        $where = [];
        if($filterCity > -10000){
            $where[] = "Apps\Common\Models\OmBanner.city_id = $filterCity";
            $this -> view -> setVar("filterCity", $filterCity);
        }
        if($banner_name > -10000){
            $where[]="banner_name = $banner_name";
            $this->view->setVar("banner_name",$banner_name);
        }
        $where[]="state = 1";
        $whereStr = implode ( ' AND ', $where );
        $total = OmBanner::count($whereStr);
        $data = OmBanner::query()
        -> columns([
            'banner_id',
            'banner_name',
            'banner_data',
            'banner_addtime',
            'Apps\Common\Models\OmBanner.city_id',
            'soc.city_name',
        ])
        ->leftJoin ( 'Apps\Common\Models\SysOpenCity', 'soc.city_id=Apps\Common\Models\OmBanner.city_id', 'soc' )
        ->where($whereStr)
        ->limit($limit, $offset)
        ->orderBy('banner_addtime DESC,banner_id DESC')
        ->execute() -> toArray();
        //处理banner_data的数据
        foreach ($data as $k=>$v){
            $data[$k]['banner_data'] = json_decode($data[$k]['banner_data'],true);     
        }
        $this->view->setVar('data',$data);
        $this->view->setVar('total', $total);
        $this->view->setVar('page', $page);
        $this->view->setVar('limit', $limit);
        
        
        $this -> view -> setVar('openCity', $this -> openCityList());
        $this -> view -> setVar('filterCity', $filterCity);
        $this -> view -> pick("om/bannerList");
    }
    
    /**
     * 添加Banner
     * @date: 2016年1月5日 
     * @author: chenxiaolin
     */
    public function bannerAddAction(){
        $this -> setLeftNav('bannerAdd');
        $req = $this -> request;
        if(!$req->isPost()){
            $this->view->setVar ( 'openCity', $this -> openCityList() );
            return;
        }else{
            $response = new ResponseResult();
            $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
            $response->callbackJavascriptTag = true;
            
            $city = $req -> getPost('city');
            $banner_name = $req -> getPost('banner_name');
            $handle_type = $req -> getPost('handle_type');
            if($handle_type == 'info'){//2.0.1版本新增需求：内容详情
                $handle_data = $req -> getPost('handle_info');
            }else{
                $handle_data = $req -> getPost('handle_data');
            }
            //判断空数据
            if(empty($city) || empty($banner_name) || empty($handle_type)){
                $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'参数异常！');
                return $response;
            }
            if($handle_type != 'none' && empty($handle_data)){
                $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'填写处理数据或内容详情！');
                return $response;
            }
            
            //判断Url是否合法
            if($handle_type == 'url' && !Util::CheckUrl($handle_data)){
                $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, 'Url不合法！');
                return $response;
            }
            //不跳转
            if($handle_type == 'none'){
                $handle_data_arr = null;
            }
            //内部打开网页
            if($handle_type == 'url'){
                $handle_data_arr = [
                    'link' => $handle_data
                ];
            }
            //跳转详情
            if($handle_type != 'none' && $handle_type != 'url'){
                $handle_data_arr = [
                    'id' => $handle_data
                ];
            }
            //2.0.1版本新增需求：内容详情
            if($handle_type == 'info'){
                $handle_data_arr = [
                    'info' => $handle_data
                ];
            }
            //上传封面
            $uploadFile = new UploadPic();
            $uploadFile -> request = $req;
            $cover = $uploadFile -> bannerPics();
            if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
                if($_FILES['banner_cover']['error'] == 1) {
                    $response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了1M！');
                    return  $response;
                }else {
                    $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, 'banner封面必须上传！');
                    return  $response;
                }
            }
            $arr = [
                'url' => $cover[0],
                'link_type' => $handle_type,
                'link_data' => json_encode($handle_data_arr)
            ];
            //循环添加数据
            foreach ($city as $k => $v){
                $banner = new OmBanner();
                $banner -> city_id = $v;
                $banner -> banner_name = $banner_name;
                $banner -> banner_addtime = date('Y-m-d H:i:m');
                $banner -> banner_update_time = date('Y-m-d H:i:m');
                $banner -> banner_data = json_encode($arr);
                $banner -> state = 1;
                $id = $banner -> save();
                if($id){//添加成功
                    $response->sendResult($id);
                }else{//添加失败
                    $this->databaseErrorLog($banner);
                    $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
                }
            }
            return $response;
        }
    }
    
    /**
     * 修改：banner
     * @date: 2016年1月8日 
     * @author: chenxiaolin
     */
    public function bannerEditAction(){
        $this -> setLeftNav('bannerEdit');
        $req = $this -> request;
        if(!$req -> isPost()){
            $id = $req -> getQuery('banner_id');
            $info = OmBanner::findFirst("banner_id = $id");
            $bannerData = json_decode($info -> banner_data,true);
            $handleData = json_decode($bannerData['link_data'],true);
            //处理banner_data字段数据
            if($bannerData['link_type'] == 'url'){
                $data = [
                    'data' => $handleData['link']
                ];
            }elseif ($bannerData['link_type'] == 'none'){
                $data = [
                    'data' => ''
                ];
            }elseif ($bannerData['link_type'] == 'info'){//2.0.1版本新增需求：内容详情
                $data = [
                    'info' => $handleData['info']
                ];
            }else{
                $data = [
                    'data' => $handleData['id']
                ];
            }
            
            $this -> view -> setVar('info', $info);
            $this -> view -> setVar('bannerData', $bannerData);
            $this -> view -> setVar('data', $data);
            $this -> view -> setVar('openCity', $this -> openCityList());
            return;
        }else{
            $response = new ResponseResult();
            $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
            $response->callbackJavascriptTag = true;
    
            $id = $req -> getPost('banner_id');
            $banner_name = $req -> getPost('banner_name');
            $handle_type = $req -> getPost('handle_type');
            if($handle_type == 'info'){//2.0.1版本新增需求：内容详情
                $handle_data = $req -> getPost('handle_info');
            }else{
                $handle_data = $req -> getPost('handle_data');
            }
    
            $data = OmBanner::findFirst("banner_id = $id");
            //判断空数据
            if(empty($banner_name) || empty($handle_type)){
                $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'参数异常！');
                return $response;
            }
            if($handle_type != 'none' && empty($handle_data)){
                $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'填写处理数据或内容详情！');
                return $response;
            }
            
            //判断Url是否合法
            if($handle_type == 'url' && !Util::CheckUrl($handle_data)){
                $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, 'Url不合法！');
                return $response;
            }
            
            //不跳转
            if($handle_type == 'none'){
                $handle_data = null;
                $handle_data_arr = null;
            }
            //内部打开网页
            if($handle_type == 'url'){
                $handle_data_arr = [
                    'link' => $handle_data
                ];
            }
            //跳转详情
            if($handle_type != 'none' && $handle_type != 'url'){
                $handle_data_arr = [
                    'id' => $handle_data
                ];
            } 
            //2.0.1版本新增需求：内容详情
            if($handle_type == 'info'){
                $handle_data_arr = [
                    'info' => $handle_data
                ];
            }
            //上传封面
            if($_FILES['banner_cover']['name']!=''){//封面不为空
                $uploadFile = new UploadPic();
                $uploadFile -> request = $req;
                $cover = $uploadFile -> bannerPics();
                if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false){
                    if($_FILES['banner_cover']['error'] == 1){
                        $response -> sendError(ResponseResultStatus::UPLOAD_FILE_ERROR,'封面大小不能超过1M！');
                    }else{
                        $response -> sendError(ResponseResultStatus::UPLOAD_FILE_ERROR,'封面必须上传！');
                    }
                    return $response;
                }
                $arr = [
                    'url' => $cover[0],
                    'link_type' => $handle_type,
                    'link_data' => json_encode($handle_data_arr)
                ];
            }else{//封面为空
               $banner_datas =  json_decode($data -> banner_data,true);
               $arr = [
                   'url' => $banner_datas['url'],
                   'link_type' => $handle_type,
                   'link_data' => json_encode($handle_data_arr)
               ];
            }
            
            $data -> banner_name = $banner_name;
            $data -> banner_data = json_encode($arr);
            $data -> banner_update_time = date('Y-m-d H:i:m');    
            if ($data -> save()){
                $response->sendResult('ok');
                return $response;
            }
    
        }
    }
    
    /**
     * 删除banner
     * @date: 2016年1月8日 
     * @author: chenxiaolin
     */
    public function bannerDeleteAction(){
        $req = $this->request;
        if ($req->isPost ()) {
            $response = new ResponseResult();
            $response->callbackJavascriptTag = true;
        
            $id = intval ( $req->getPost ( 'id', null, 0 ) );
            $state = $req->getPost ( 'state', null, 0 );
            $info = OmBanner::findFirst ( 'banner_id = ' . $id );
        
            if($info){
                $info -> update([
                    'state' => $state
                ]);
            }
            $arr=[
                'status'=>10000
            ];
            echo json_encode($arr);
             
        } else {
            $arr=[
                'status'=>0,
                'error'=>'请求异常！'
            ];
            echo json_encode($arr);
        }
    }
    
    /**
     * 广告位列表
     * @date: 2016年1月7日 
     * @author: chenxiaolin
     */
    public function advertisementListAction(){
        $this -> setLeftNav('advertisementList');
        $req = $this->request;
        $page = intval($req->getQuery('page', null, 1));
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $offset = $limit * ($page - 1);
        
        $filterCity = $req -> getQuery('filterCity',null,-10000);
        $title = $req -> getQuery('advertisement_title');
        $where = [];
        if($filterCity > -10000){
            $where[] = "Apps\Common\Models\Advertisement.city_id = $filterCity";
        }
        if($title != ''){
            $where[]="advertisement_title like '%".$title."%'";
            $this->view->setVar("advertisement_title",$title);
        }
        $whereStr = implode ( ' AND ', $where );
        $total = Advertisement::count($whereStr);
        $data = Advertisement::query()
        -> columns([
            'advertisement_id',
            'advertisement_cover',
            'advertisement_title',
            'position',
            'addtime',
            'Apps\Common\Models\Advertisement.city_id',
            'soc.city_name',
        ])
        ->leftJoin ( 'Apps\Common\Models\SysOpenCity', 'soc.city_id=Apps\Common\Models\Advertisement.city_id', 'soc' )
        ->where($whereStr)
        ->limit($limit, $offset)
        ->orderBy('addtime DESC')
        ->execute() -> toArray();
        //处理广告封面
        foreach ($data as $k=>$v){
            $data[$k]['advertisement_cover']=PicUrl::AdvertisementPic($data[$k]['advertisement_cover'], $this->getDi());
        }
        $this->view->setVar('data',$data);
        $this->view->setVar('total', $total);
        $this->view->setVar('page', $page);
        $this->view->setVar('limit', $limit);
        $this -> view -> setVar("filterCity", $filterCity);
        $this -> view -> setVar('openCity', $this -> openCityList());
    }
    
    /**
     * 广告位添加
     * @date: 2016年1月7日 
     * @author: chenxiaolin
     */
    public function advertisementAddAction(){
        $this -> setLeftNav('advertisementAdd');
        $req = $this -> request;
        $response = new ResponseResult();
        $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
        $response->callbackJavascriptTag = true;
        if(!$req -> isPost()){
            $this -> view -> setVar('openCity', $this -> openCityList());
            return;
        }else{
            $city = $req -> getPost('city');
            $title = $req -> getPost('advertisement_title');
            $position = $req -> getPost('position');
            $type = $req -> getPost('type');
            $intro = $req -> getPost('advertisement_intro');
            $out_link = $req -> getPost('out_link');
            
            
            //判断空数据
            if($type <= 0 || empty($title) || $position <= 0 || $city < 0){
                $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'参数异常！');
                return $response;
            }
            
            //判断图文介绍还是外链地址
            if($type == 1 && empty($intro)){
                $response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请填写图文介绍！' );
                return $response;
            }
            if($type == 2 && empty($out_link)){
                $response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请填写外链地址！' );
                return $response;
            }
            
            //判断外链地址是否合法
            if($type == 2 && !Util::CheckUrl($out_link)){
                $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '外链地址不合法！');
                return $response;
            }
            
            //全国广告位与城市广告位互斥
            if(in_array(0,$city)){//全国广告
                $cityAdNum = Advertisement::count("city_id not in ( 0 ) and position = $position");
                //查询此广告位是否已存在数据
                if($cityAdNum > 0){
                    $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'此广告位已被城市占用！');
                    return $response;
                }
                //该全国广告位是否已存在数据
                $ad = Advertisement::findFirst("city_id = 0 and position = $position");
                if($ad){
                    $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'此广告位已有数据！');
                    return $response;
                }
            }else{//城市广告
               //查询全国此广告位是否已存在数据
               $countryAd = Advertisement::findFirst("city_id = 0 and position = $position");
               if($countryAd){
                   $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'此广告位已被全国占用！');
                   return $response;
               }
               //该城市广告位是否已存在数据
               foreach ($city as $k => $v){
                   $ad = Advertisement::findFirst("city_id = $v and position = $position");
                   //某城市该广告位存在数据
                   if($ad){
                       $citys = SysOpenCity::findFirst("city_id = $v");
                       $city_name = $citys -> city_name;
                       $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,$city_name."此广告位已有数据！");
                       return $response;
                   }
               }
            }
            
            
            //保存封面
            $uploadFile = new UploadPic();
            $uploadFile->request = $req;
            $cover = $uploadFile->advertisementPics();
            if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
                if($_FILES['advertisement_cover']['error'] == 1) {
                    $response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了1M！');
                    return  $response;
                }else {
                    $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '广告封面必须上传！');
                    return  $response;
                }
            }
            $cover = $cover[0];
            
            foreach ($city as $k => $v){
            
                $adv = new Advertisement();
                $adv -> advertisement_title = $title;
                $adv -> advertisement_cover = $cover;
                $adv -> position = $position;
                $adv -> type = $type;
                if($type == 1){
                    $adv -> advertisement_intro = $intro;
                    $adv -> out_link = '';
                }
                if($type == 2){
                    $adv -> out_link = $out_link;
                    $adv -> advertisement_intro = '';
                }
                
                $adv -> addtime = date('Y-m-d H:i:m');
                $adv -> city_id = $v;
                $status = $adv -> save();
                
                if($status === false) {
                    $this->databaseErrorLog($adv);
                    $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
                } else {
                    $response->sendResult($status);
                }
            }
            return $response;
        }
        
    }
    
    /**
     * 删除广告
     * @date: 2016年1月7日 
     * @author: chenxiaolin
     */
    public function advertisementDeleteAction(){
        $req = $this->request;
        if ($req->isPost ()) {
            $response = new ResponseResult(); 
            $response->callbackJavascriptTag = true;
        
            $id = intval ( $req->getPost ( 'id', null, 0 ) );           	
            $info = Advertisement::findFirst ( 'advertisement_id = ' . $id );
        
            if($info){
                $info -> delete();
            }
               $arr=[
                   'status'=>10000
               ];
               echo json_encode($arr);
               
        } else {
            $arr=[
                'status'=>0,
                'error'=>'请求异常！'
            ];
            echo json_encode($arr);
        }
    }
    
    /**
     * 修改广告位
     * @date: 2016年1月7日 
     * @author: chenxiaolin
     */
    public function advertisementEditAction(){
        $this -> setLeftNav('advertisementEdit');
        $req = $this -> request;
        if(!$req -> isPost()){
            $id = $req -> getQuery('id');
            $info = Advertisement::findFirst("advertisement_id = $id");
            $info -> advertisement_cover = PicUrl::AdvertisementPic($info -> advertisement_cover, $this -> getDI());
            $this -> view -> setVar('info', $info);
            $this -> view -> setVar('openCity', $this -> openCityList());
            return;
        }else{
            $response = new ResponseResult();
            $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
            $response->callbackJavascriptTag = true;
            
            $id = $req -> getPost('advertisement_id');
            $title = $req -> getPost('advertisement_title');
            $position = $req -> getPost('position');
            $type = $req -> getPost('type');
            $intro = $req -> getPost('advertisement_intro');
            $out_link = $req -> getPost('out_link');
            
            
            //判断空数据
            if($type <= 0 || empty($title) || $position <= 0 || $city < 0){
                $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'参数异常！');
                return $response;
            }
            
            //判断图文介绍还是外链地址
            if($type == 1 && empty($intro)){
                $response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请填写图文介绍！' );
                return $response;
            }
            if($type == 2 && empty($out_link)){
                $response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请填写外链地址！' );
                return $response;
            }
            
            //判断外链地址是否合法
            if($type == 2 && !Util::CheckUrl($out_link)){
                $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '外链地址不合法！');
                return $response;
            }
            
            //判断该广告位是否有数据
            $data = Advertisement::findFirst("advertisement_id = $id");
            
            if($data -> position != $position){
                $city = $data -> city_id;
                //判断当前城市的此广告位是否已有数据
                $ad = Advertisement::findFirst("city_id = $city and position = $position");
                if($ad){
                    $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'此广告位已有数据！');
                    return $response;
                }
                //修改全国数据时：判断此广告位是否已被其他城市占用
                if($city == 0){
                    $num = Advertisement::count("city_id not in ( 0 ) and position = $position");
                    if($num > 0){
                        $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'此广告位已被城市占用！');
                        return $response;
                    }
                }else{
                    //修改城市数据时：判断此广告位是否已被全国占用
                    $countryAd = Advertisement::findFirst("city_id = 0 and position = $position");
                    if($countryAd){
                        $response -> sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY,'此广告位已被全国占用！');
                        return $response;
                    }
                }
                
            }
            //修改封面
            if($_FILES['advertisement_cover']['name']!=''){
                $uploadFile = new UploadPic();
                $uploadFile -> request = $req;
                $cover = $uploadFile -> advertisementPics();
                if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false){
                    if($_FILES['advertisement_cover']['error'] == 1){
                        $response -> sendError(ResponseResultStatus::UPLOAD_FILE_ERROR,'封面大小不能超过1M！');
                    }else{
                        $response -> sendError(ResponseResultStatus::UPLOAD_FILE_ERROR,'封面必须上传！');
                    }
                    return $response;
                }
                $data -> advertisement_cover = $cover[0];
            }              
            $data -> advertisement_title = $title;
            $data -> position = $position;
            $data -> type = $type;
            if($type == 1){
                $data -> advertisement_intro = $intro;
                $data -> out_link = '';
            }
            if($type == 2){
                $data -> out_link = $out_link;
                $data -> advertisement_intro = '';
            }
            
            
            if ($data -> save()){
                $response->sendResult('ok');
                return $response;
            }
            
        }
    }
    
    /**
     * 开通城市管理列表
     * @date: 2016年1月6日 
     * @author: chenxiaolin
     */
    public function openCityListAction()
    {
        $this->setLeftNav('openCityList');
        $req = $this->request;
        $page = intval ( $req->getQuery ( 'page', null, 1 ) );
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $offset = $limit * ($page - 1);
        
        $filterCity = $req -> getQuery('filterCity',null,-10000);
        $filterState = $req -> getQuery('filterState',null,-10000);
        $where = [];
        if($filterCity > -10000){
           $where[] = " city_id = $filterCity "; 
        }
        
        if($filterState > -10000){
            $where[] = " city_state = $filterState ";
        }
        $whereStr = implode ( ' AND ', $where );
        $data = SysOpenCity::query()
            -> where($whereStr)
            ->execute();
        $this -> view -> setVar('openCity', SysOpenCity::find());
        $this -> view -> setVar('filterCity', $filterCity);
        $this -> view -> setVar('filterState', $filterState);
        //$this->view->setVar('data', SysOpenCity::find($where));
        $this->view->setVar('data', $data);
    }

    /**
     * 添加开通的城市
     */
    public function openCityAddAction()
    {
        $req = $this->request;
        if(!$req->isPost()) {
            return;
        }
        $response = new ResponseResult();
        $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
        $response->callbackJavascriptTag = true;

        $province = $req->getPost('province', null, '');
        $city = $req->getPost('city', null, '');
        if(empty($province) || empty($city)) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数问题！');
            return $response;
        }
        // 获取地区数据信息
        if($city != '1') {
            $info = SysAreaZipDistrictPhonecode::query()
                ->where('C_NM = :nm:', ['nm' => $city])
                ->execute()
                ->getFirst();
        } else {
            $info = SysAreaZipDistrictPhonecode::query()
                ->where('P_NM = :nm:', ['nm' => $province])
                ->execute()
                ->getFirst();
        }
        if(!$info) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数问题！');
            return $response;
        }
        // 判断是否存在
        if(SysOpenCity::count('city_code = ' . $info->PHONE_CODE) > 0) {
            $response->sendError(ResponseResultStatus::BUSINESS, '已经存在！');
            return $response;
        }
        $cityInfo = new SysOpenCity();
        $cityInfo->city_code = $info->PHONE_CODE;
        $cityInfo->city_name = $city != '1' ? $info->C_NM : $info->P_NM;
        $cityInfo->city_order = 0;
        $cityInfo->city_state = 0;

        if($cityInfo->save() == false) {
            $this->databaseErrorLog($cityInfo);
            $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
        } else {
            $response->sendResult($cityInfo->city_id);
        }
        return $response;
    }

    /**
     * 设置开通城市的状态
     * @return $this|ResponseResult
     */
    public function openCitySetStateAction()
    {
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $state = intval($req->getPost('state', null, -10000));
            if(!in_array($state, [-1, 0, 1])) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            $info = SysOpenCity::findFirst('city_id=' . $id);
            if($info) {
                $info->update(['city_state' => $state]);
            }
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }

    /**
     * 设置开通城市的排序值1.0
     * @return $this|ResponseResult
     */
    public function openCitySetOrderAction()
    {
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $order = intval($req->getPost('order', null, 0));
            if($order < 0) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            $info = SysOpenCity::findFirst('city_id=' . $id);
            if($info) {
                $info->update(['city_order' => $order]);
            }
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }

    /**
     * 设置回到问题的用户账号关联1.0
     */
    public function questionUserAction()
    {
        $this->setLeftNav('questionUser');
        $data = OmQuestionAnswerUser::query()
            ->columns([
                'qau_id',
                'op.operator_id',
                'op.operator_account',
                'op.operator_show_name',
                'ub.user_id',
                'ub.user_account',
                'ub.user_nickname',
            ])
            ->leftJoin('Apps\Common\Models\UserBase', 'ub.user_id = Apps\Common\Models\OmQuestionAnswerUser.user_id', 'ub')
            ->leftJoin('Apps\Common\Models\BackendOperator', 'op.operator_id=op_id', 'op')
            ->execute();
        $this->view->setVar('data', $data);
    }

    /**
     * 删除关联数据1.0
     * @return $this|ResponseResult
     */
    public function questionUserSetStateAction()
    {
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $state = intval($req->getPost('state', null, 0));
            if(!in_array($state, [-1, 0, 1])) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            $info = OmQuestionAnswerUser::findFirst('qau_id=' . $id);
            if($info) {
                $info->delete();
            }
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }

    /**
     * 添加关联1.0
     */
    public function questionUserAddAction()
    {
        $req = $this->request;
        if(!$req->isPost()) {
            $this->view->setVar('opList', BackendOperator::find('operator_group = 2'));
            return;
        }
        $response = new ResponseResult();
        $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
        $response->callbackJavascriptTag = true;

        $opId = intval($req->getPost('op_id', null, 0));
        $userId = intval($req->getPost('user_id', null, 0));

        if($opId < 1 || $userId < 1) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数问题！');
            return $response;
        }
        // 操作员是否存在
        if(BackendOperator::count('operator_id = ' . $opId) == 0) {
            $response->sendError(ResponseResultStatus::BUSINESS, '操作员不存在！');
            return $response;
        }
        // 用户是否存在
        if(UserBase::count('user_id = ' . $userId) == 0) {
            $response->sendError(ResponseResultStatus::BUSINESS, '用户不存在！');
            return $response;
        }
        $info = new OmQuestionAnswerUser();
        $info->op_id = $opId;
        $info->user_id = $userId;

        if($info->save() == false) {
            $this->databaseErrorLog($info);
            $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
        } else {
            $response->sendResult($info->qau_id);
        }
        return $response;
    }

    /**
     * 用户反馈列表
     * @date: 2016年1月6日 
     * @author: chenxiaolin
     */    
    public function userFeedbackAction()
    {
        $this->setLeftNav('userFeedback');
        $req = $this->request;
        $page = intval($req->getQuery('page', null, 1));
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $offset = $limit * ($page - 1);
        
        $filterCity = $req -> getQuery('filterCity',null,-10000);
        $feedback_content = $req -> getQuery('feedback_content');
        $where = [];
        if($filterCity > -10000){
            $where[] = "Apps\Common\Models\UserFeedback.city_id = $filterCity";
            $this -> view -> setVar("filterCity", $filterCity);
        }
        if($feedback_content != ''){
            $where[]="feedback_content like '%".$feedback_content."%'";
            $this->view->setVar("feedback_content",$feedback_content);
        }
        $whereStr = implode ( ' AND ', $where );
        $total = UserFeedback::count($whereStr);
        $data = UserFeedback::query()
            -> columns([
                'feedback_id',
                'feedback_contact',
                'feedback_content',
                'feedback_addtime',
                'soc.city_name',
            ])
            ->leftJoin ( 'Apps\Common\Models\SysOpenCity', 'soc.city_id=Apps\Common\Models\UserFeedback.city_id', 'soc' )
            ->where($whereStr)
            ->limit($limit, $offset)
            ->orderBy('feedback_addtime DESC')
            ->execute();
            
        $this->view->setVar('data',$data);
        $this->view->setVar('total', $total);
        $this->view->setVar('page', $page);
        $this->view->setVar('limit', $limit);
        $this -> view -> setVar('openCity', $this -> openCityList());
    }
    
    /**
     * 问答举报列表
     * @date: 2016年1月6日 
     * @author: chenxiaolin
     */
    public function questionReportAction(){
        $this -> setLeftNav('questionReport');
        $req = $this->request;
        $page = intval($req->getQuery('page', null, 1));
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $offset = $limit * ($page - 1);
        
        $city = SysAreaZipDistrictPhonecode::query()
            -> columns([
                'P_NM',
                'PHONE_CODE'
            ])
            -> groupBy('P_NM')
            ->execute(); 
        $filterCity = $req -> getQuery('filterCity',null,-10000);
        $report_content = $req -> getQuery('report_content');
        $where = [];
        if($filterCity > -10000){
            $where[] = "Apps\Common\Models\QuestionReport.city_code = $filterCity";
            $this -> view -> setVar("filterCity", $filterCity);
        }
        if($report_content != ''){
            $where[]="report_content like '%".$report_content."%'";
            $this->view->setVar("report_content",$report_content);
        }
        $whereStr = implode ( ' AND ', $where );
        $total = QuestionReport::count($whereStr);
        $data = QuestionReport::query()
        -> columns([
            'distinct report_id',
            'report_content',
            'user.bind_phone',
            'question_id',
            'report_addtime',
            'user.user_nickname',
            'area.P_NM as city_name',
        ])
        ->leftJoin ( 'Apps\Common\Models\SysAreaZipDistrictPhonecode', 'area.PHONE_CODE=Apps\Common\Models\QuestionReport.city_code', 'area' )
        ->leftJoin ( 'Apps\Common\Models\UserBase', 'user.user_id=Apps\Common\Models\QuestionReport.user_id', 'user' )
        ->where($whereStr)
        ->limit($limit, $offset)
        ->orderBy('report_addtime DESC')
        ->execute();
        
        $this->view->setVar('data',$data);
        $this->view->setVar('total', $total);
        $this->view->setVar('page', $page);
        $this->view->setVar('limit', $limit);
        $this -> view -> setVar('city', $city);
    }
    
    /**
     * 首页添加推荐美容院(新增功能)
     */
    public function bannerBpAddAction()
    {
    	
    	$this->setLeftNav('bannerBp');
    	$req = $this -> request;
    	if(!$req->isPost()) {
            $this->view->setVar('openCity', $this->openCityList());
            $this->view->pick("om/bannerBpAdd");
    		return;
    	}
    
    	$response = new ResponseResult();
    	$response->callback = $req->getPost('callback', null, 'parent.setFormResult');
    	$response->callbackJavascriptTag = true;
    
    	$bp_id =  intval($req -> getPost('bp_id'));
    	$city = $req -> getPost('city');
    	$addr = $city;
    	$sort = $req -> getPost('sort');
    	
    
    	// 判断空数据
    	if(empty($bp_id) || empty($addr) || empty($sort)) {
    		$response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！');
    		return $response;
    	}
    	//判断要推荐的美容是否存在
    	$bp = BeautyParlor::findFirst(" bp_id = $bp_id and bp_state = 1");
		if(empty($bp)){
			$response->sendError(ResponseResultStatus::BUSINESS, '当前推荐的美容院不存在或未发布或已删除！');
			return $response;
		}
    	//保存推荐美容院图片
    	$uploadFile = new UploadPic();
    	$uploadFile->request = $req;
    	$cover = $uploadFile ->beautyParlorCover();
    	
    	if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {    		 
    		 
    		if($_FILES['bp_cover']['error'] == 1) {
    			$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了1M！');
    		}
    		return $response;
    	}
	
    	//判断美容院是否已经存在3个
    	if(CosPointBp::count("addr = $addr") >= 3){
    		$response->sendError(ResponseResultStatus::BUSINESS, '首页推荐美容院只能添加3个！');
    		return $response;
    	}
    
    	//判断要添加的美容院是否已存在
    
    	if(CosPointBp::count('bp_id = ' . $bp_id.' and addr = '.$addr)){
    		$response->sendError(ResponseResultStatus::BUSINESS, '该美容院已经加入首页推荐！');
    		return $response;
    	}elseif(CosPointBp::count('sort = ' . $sort . ' and addr = '.$addr)){
    		$response->sendError(ResponseResultStatus::BUSINESS, '排序已经存在！');
    		return $response;
    	}
    
    	//实例化Model,组装数据
    	$cosPointBp = new CosPointBp();
    	$cosPointBp -> bp_id = $bp_id;
    	$cosPointBp -> addr = $addr;
    	$cosPointBp -> sort = $sort;
    	$cosPointBp -> img_url = $cover[0];
    	//保存数据
    	if($cosPointBp->save() == false) {
    		$this->databaseErrorLog($cosPointBp);
    		$response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
    	} else {
    		$response->sendResult($cosPointBp->id);
    	}
    	return $response;
    }
    /**
     * 取消首页推荐美容院1.0
     */
    public function calloffAction(){
    	$req=$this->request;
    	$id=$req->getQuery("id");
    	$cityid=$req->getQuery("city_id");
    	$flg=CosPointBp::find("id = $id")->delete();
    	if($flg==true){
    		echo "<script>location.href='/manage/om/bannerBp?City=$cityid'</script>";
    	}
    	
    }
}